import {getRecommendListAPI, getTodayBestAPI} from "../../api"
import React, {useEffect, useState} from "react"
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Image,
  FlatList,
  Dimensions,
  Alert,
} from "react-native"
import LinearGradient from "react-native-linear-gradient"
import {RecommendItem, RecommendParams, RecommendResult} from "types/friend"
import {useTHNavigation} from "../../utils/navigation"
import {useLoading, useShowToast} from "../../hooks"

const {width} = Dimensions.get("window")

const CARD_GAP = 4
const CARD_WIDTH = (width - 4 * 2 - CARD_GAP) / 2 // 12*2是左右padding

const menuList = [
  {label: "测灵魂", color: "#FFD452"},
  {label: "探花", color: "#FF5B5B"},
  {label: "搜附近", color: "#3EC6FF"},
  {label: "桃花运", color: "#B07CFF"},
]

const todayBest = {
  avatar: require("../../res/default_user.jpg"),
  name: "黑马小妹",
  age: 26,
  info: "单身 | 本科 | 年龄相仿",
  fateValue: 98,
}

const Friend = () => {
  const [recommendList, setRecommentList] = useState<RecommendResult>([])
  const [loading, setLoading] = useState(false)
  const [finished, setFinished] = useState(false)
  const showToast = useShowToast()
  const showLoading = useLoading()

  const params: RecommendParams = {
    page: 1,
    pagesize: 10,
    gender: "女",
    lastLogin: "无限制",
    distance: -1,
    city: "",
    education: "",
  }
  const getRecommendList = async () => {
    const close = showLoading()
    try {
      const res = await getRecommendListAPI(params)
      if (!res?.length) {
        setFinished(true) // 没有数据了
      }
      setRecommentList([...recommendList, ...res])
    } catch (error) {
      setFinished(true) // 没有数据了
    } finally {
      close()
    }
  }
  const getTodayBest = async () => {
    const res = await getTodayBestAPI()
    // Alert.alert(JSON.stringify(res))
  }
  useEffect(() => {
    getTodayBest()
    getRecommendList()
  }, [])

  // 获取下一页数据
  const getNextRecommend = async () => {
    if (finished) {
      showToast("没有数据了")
      return
    }
    if (!loading) {
      setLoading(true)
      params.page++ // 页码+1
      await getRecommendList()
      setLoading(false)
    }
  }
  const navigaiton = useTHNavigation()

  const renderRecommendItem = ({
    item,
    index,
  }: {
    item: RecommendItem
    index: number
  }) => (
    <TouchableOpacity
      onPress={() =>
        navigaiton.push("Chat", {
          id: item.id,
        })
      }>
      <View
        style={[
          styles.recommendCard,
          {marginRight: index % 2 === 0 ? CARD_GAP : 0},
        ]}>
        <Image
          source={{
            uri: item.header.includes("http")
              ? item.header
              : "http://api-tanhua-harmony.itheima.net" + item.header,
          }}
          style={styles.recommendAvatar}
        />
        <TouchableOpacity style={styles.recommendFate}>
          <Text style={styles.recommendFateText}>❤️{item.fateValue}</Text>
        </TouchableOpacity>
        <View style={styles.recommendInfo}>
          <Text style={styles.recommendName}>
            {item.nick_name}{" "}
            <Text style={styles.recommendAge}>🎂{item.age}</Text>
            {item.gender === "男" ? "♂" : item.gender === "女" ? "♀" : ""}
          </Text>
          <View style={styles.desInfo}>
            <Text style={styles.recommendDesc}>{item.marry}</Text>
            <Text style={styles.recommendDesc}>{item.dist}米</Text>
          </View>
        </View>
      </View>
    </TouchableOpacity>
  )
  // 跳转地址
  const toPage = (item: any) => {
    if (item.label === "探花") {
      navigaiton.push("TanHua")
    }
  }

  return (
    <View style={styles.container}>
      {/* 顶部渐变背景 */}
      <LinearGradient
        colors={["#FFB6F7", "#FF6FB7", "#6FC3FF"]}
        start={{x: 0, y: 0}}
        end={{x: 1, y: 0}}
        style={styles.gradientBg}>
        <View style={styles.menuRow}>
          {menuList.map((item, idx) => (
            <TouchableOpacity
              key={item.label}
              style={[
                styles.menuBtn,
                {backgroundColor: item.color, marginLeft: idx === 0 ? 0 : 12},
              ]}
              activeOpacity={0.8}
              onPress={() => toPage(item)}>
              <Text style={styles.menuBtnText}>{item.label}</Text>
            </TouchableOpacity>
          ))}
        </View>
      </LinearGradient>

      {/* 今日佳人卡片 */}
      <View style={styles.todayCard}>
        <Image source={todayBest.avatar} style={styles.todayAvatar} />
        <View style={styles.todayInfo}>
          <Text style={styles.todayName}>
            {todayBest.name}{" "}
            <Text style={styles.todayAge}>🎂{todayBest.age}</Text>
          </Text>
          <Text style={styles.todayDesc}>{todayBest.info}</Text>
        </View>
        <View style={styles.todayFate}>
          <Text style={styles.todayFateText}>{todayBest.fateValue}</Text>
        </View>
      </View>

      {/* 推荐标题 */}
      <Text style={styles.recommendTitle}>推荐</Text>

      {/* 推荐列表 */}
      <FlatList
        data={recommendList}
        renderItem={({item, index}) => renderRecommendItem({item, index})}
        keyExtractor={item => item.id.toString()}
        numColumns={2}
        columnWrapperStyle={{
          paddingHorizontal: 4,
          paddingVertical: 4,
        }}
        contentContainerStyle={{paddingBottom: 20}}
        showsVerticalScrollIndicator={false}
        onEndReached={getNextRecommend}
      />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {flex: 1, backgroundColor: "#F2FAFF"},
  gradientBg: {
    height: 160,
    borderBottomLeftRadius: 24,
    borderBottomRightRadius: 24,
    justifyContent: "flex-end",
    paddingBottom: 12,
    paddingHorizontal: 16,
  },
  menuRow: {
    flexDirection: "row",
    justifyContent: "space-between",
  },
  menuBtn: {
    flex: 1,
    height: 56,
    borderRadius: 16,
    justifyContent: "center",
    alignItems: "center",
    elevation: 4,
    shadowColor: "#000",
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.08,
    shadowRadius: 4,
  },
  menuBtnText: {
    color: "#fff",
    fontWeight: "bold",
    fontSize: 16,
  },
  todayCard: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#fff",
    marginHorizontal: 16,
    marginTop: 32,
    borderRadius: 20,
    padding: 16,
    elevation: 2,
    shadowColor: "#000",
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.08,
    shadowRadius: 4,
  },
  todayAvatar: {
    width: 48,
    height: 48,
    borderRadius: 24,
    marginRight: 12,
  },
  todayInfo: {flex: 1},
  todayName: {fontSize: 16, fontWeight: "bold", color: "#333"},
  todayAge: {fontSize: 14, color: "#FE5072"},
  todayDesc: {fontSize: 13, color: "#888", marginTop: 4},
  todayFate: {
    backgroundColor: "#FE5072",
    borderRadius: 20,
    paddingHorizontal: 16,
    paddingVertical: 6,
    alignItems: "center",
    justifyContent: "center",
  },
  todayFateText: {color: "#fff", fontWeight: "bold", fontSize: 18},
  recommendTitle: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#333",
    marginTop: 18,
    marginLeft: 16,
    marginBottom: 8,
  },
  recommendCard: {
    backgroundColor: "#fff",
    borderRadius: 16,
    width: CARD_WIDTH,
    height: 220,
    overflow: "hidden",
    elevation: 1,
    shadowColor: "#000",
    shadowOffset: {width: 0, height: 1},
    shadowOpacity: 0.06,
    shadowRadius: 2,
    position: "relative",
  },
  recommendAvatar: {
    width: "100%",
    height: 140,
    borderTopLeftRadius: 16,
    borderTopRightRadius: 16,
    resizeMode: "cover",
  },
  recommendFate: {
    position: "absolute",
    right: 8,
    top: 8,
    backgroundColor: "#FE5072",
    borderRadius: 12,
    paddingHorizontal: 8,
    paddingVertical: 2,
    zIndex: 2,
  },
  recommendFateText: {
    color: "#fff",
    fontSize: 13,
    fontWeight: "bold",
  },
  recommendInfo: {
    padding: 8,
  },
  recommendName: {
    fontSize: 15,
    fontWeight: "bold",
    color: "#333",
  },
  recommendAge: {
    fontSize: 13,
    color: "#2DB3F8",
  },
  recommendDesc: {
    fontSize: 12,
    color: "#888",
    marginTop: 2,
    justifyContent: "space-between",
  },
  desInfo: {
    height: 40,
    display: "flex",
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
  },
})

export default Friend
